package com.xinchuang.service.impl;


import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.DateUtil;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.xinchuang.comment.LogConstant;
import com.xinchuang.comment.R;
import com.xinchuang.domain.entity.DictTable;
import com.xinchuang.domain.entity.DictType;
import com.xinchuang.manager.DictTableService;
import com.xinchuang.manager.DictTypeService;
import com.xinchuang.service.DictionaryModService;
import com.xinchuang.utils.HanyuPinyinUtil;
import com.xinchuang.utils.IdUtils;
import com.xinchuang.utils.MyUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

import com.alibaba.fastjson.JSON;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletRequest;

@Service
public class DictionaryModServiceImpl implements DictionaryModService {

    @Autowired
    private DictTypeService dictTypeService;

    @Autowired
    private DictTableService dictTableService;

    private static SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    @Override
    public String addDicType(JSONObject jsonObject) {
        //jsonobject解析获取类型名称
        String typeName = jsonObject.getString("typeName");
        LambdaQueryWrapper<DictType> dictTypeQueryWrapper = new LambdaQueryWrapper<>();
        dictTypeQueryWrapper.eq(DictType::getTypeName, typeName);
        if (null != dictTypeService.getOne(dictTypeQueryWrapper)) {
            return JSON.toJSONString(R.fail("类型名称已存在"));
        }
        DictType dictType = new DictType(IdUtils.simpleUUID(), typeName, new Date(), new Date());
        if (dictTypeService.save(dictType)) {
            return JSON.toJSONString(R.success("保存成功"));
        }
        return JSON.toJSONString(R.fail(LogConstant.DEFAULT_FAILURE_MESSAGE));
    }

    @Override
    public String editDicType(JSONObject jsonObject) {
        //jsonobject解析获取类型Id
        String typeId = jsonObject.getString("typeId");
        //jsonobject解析获取类型名称
        String typeName = jsonObject.getString("typeName");
        //jsonobject解析获取是否是默认值
        Integer sort = jsonObject.getInteger("sort");
        LambdaUpdateWrapper<DictType> dictTypeLambdaUpdateWrapper = new LambdaUpdateWrapper<>();
        dictTypeLambdaUpdateWrapper
                .eq(DictType::getTypeId, typeId)
                .set(DictType::getTypeName, typeName)
                .set(DictType::getUpdateTime, new Date());
        boolean update = dictTypeService.update(dictTypeLambdaUpdateWrapper);
        if (update) {
            return JSON.toJSONString(R.success("编辑成功"));
        }
        return JSON.toJSONString(R.fail(LogConstant.DEFAULT_FAILURE_MESSAGE));
    }

    @Override
    @Transactional
    public String delDicType(JSONObject jsonObject) {
        //jsonobject解析获取类型ID
        String typeId = jsonObject.getString("typeId");

        LambdaQueryWrapper<DictTable> dictTableLambdaQueryWrapper = new LambdaQueryWrapper<>();
        dictTableLambdaQueryWrapper.eq(DictTable::getTypeId, typeId);
        dictTableService.remove(dictTableLambdaQueryWrapper);
        if (dictTypeService.removeById(typeId)) {
            return JSON.toJSONString(R.success("删除成功"));
        }
        return JSON.toJSONString(R.fail(LogConstant.DEFAULT_FAILURE_MESSAGE));
    }

    @Override
    public String dicList(JSONObject jsonObject) {
        //jsonobject解析获取字典类型
        String typeId = jsonObject.getString("typeId");
        //jsonobject解析获取字典值
        String dicName = jsonObject.getString("dicName");
        //jsonobject解析获取页码
        String pageNum = jsonObject.getString("pageNum");
        //jsonobject解析获取每页数量
        String pageSize = jsonObject.getString("pageSize");
        Page<DictTable> dictTablePage = new Page<>(Integer.valueOf(pageNum), Integer.valueOf(pageSize));
        LambdaQueryWrapper<DictTable> dictTableLambdaQueryWrapper = new LambdaQueryWrapper<>();
        dictTableLambdaQueryWrapper.eq(StringUtils.isNotEmpty(typeId), DictTable::getTypeId, typeId);
        dictTableLambdaQueryWrapper.like(StringUtils.isNotEmpty(dicName), DictTable::getDicName, dicName);
        dictTableLambdaQueryWrapper.orderByDesc(DictTable::getCreateTime);
        Page<DictTable> page = dictTableService.page(dictTablePage, dictTableLambdaQueryWrapper);
        HashMap<String, Object> result = new HashMap<>();
        if (CollectionUtil.isNotEmpty(page.getRecords())) {
            JSONArray resultArray = new JSONArray();
            for (DictTable record : page.getRecords()) {
                JSONObject json = new JSONObject();
                json.put("typeId", record.getTypeId());
                json.put("sort", record.getSort());
                json.put("typeName", record.getTypeName());
                json.put("dicName", record.getDicName());
                json.put("dicNamePinYin", HanyuPinyinUtil.chineseToPinyin(record.getDicName()));
                json.put("dicId", record.getDicId());
                json.put("addName", record.getAddName());
                json.put("isDefault", StringUtils.isBlank(record.getIsDefault()) ? false : Boolean.valueOf(record.getIsDefault()));
                json.put("createTime", DateUtil.format(record.getCreateTime(), "yyyy-MM-dd HH:mm:ss"));
                json.put("updateTime", DateUtil.format(record.getUpdateTime(), "yyyy-MM-dd HH:mm:ss"));
                resultArray.add(json);
            }
            result.put("dataList", resultArray);
        } else {
            result.put("dataList", page.getRecords());
        }
        result.put("totalNum", page.getTotal());
        return JSON.toJSONString(R.data(result));
    }

    @Override
    public String addDic(JSONObject jsonObject, HttpServletRequest request) {
        //jsonobject解析获取类型Id
        String typeId = jsonObject.getString("typeId");
        //jsonobject解析获取数据值
        String dicName = jsonObject.getString("dicName");
        //jsonobject解析获取是否是默认值
        String isDefault = jsonObject.getString("isDefault");
        //jsonobject解析获取是否是默认值
        Integer sort = jsonObject.getInteger("sort");

        long count = dictTableService.count(new LambdaQueryWrapper<DictTable>()
                .eq(DictTable::getTypeId, typeId)
                .eq(DictTable::getDicName, dicName));
        if (count > 0) {
            return JSON.toJSONString(R.fail("数据值已重复，请修改后重试"));
        }
        DictType dictType = dictTypeService.getById(typeId);
        if (isDefault.equals("true")) {
            dictTableService.lambdaUpdate()
                    .set(DictTable::getIsDefault, "false")
                    .eq(DictTable::getTypeId, dictType.getTypeId())
                    .update();
        }
        DictTable dictTable = new DictTable(
                IdUtils.simpleUUID(),
                dictType.getTypeName(),
                dictType.getTypeId(),
                dicName,
                isDefault,
                MyUtils.getName(MyUtils.getHeader(request).getId()),
                new Date(),
                new Date(), sort);
        boolean save = dictTableService.save(dictTable);
        if (save) {
            return JSON.toJSONString(R.success("保存成功"));
        }
        return JSON.toJSONString(R.fail(LogConstant.DEFAULT_FAILURE_MESSAGE));
    }

    @Override
    public String editDic(JSONObject jsonObject) {
        //jsonobject解析获取字典类型Id
        String typeId = jsonObject.getString("typeId");
        //jsonobject解析获取数据值
        String dicName = jsonObject.getString("dicName");
        //jsonobject解析获取数据Id
        String dicId = jsonObject.getString("dicId");
        //jsonobject解析获取是否是默认值
        String isDefault = jsonObject.getString("isDefault");
        //jsonobject解析获取是否是默认值
        Integer sort = jsonObject.getInteger("sort");
        long count = dictTableService.count(new LambdaQueryWrapper<DictTable>()
                .notIn(DictTable::getDicId, dicId)
                .eq(DictTable::getTypeId, typeId)
                .eq(DictTable::getDicName, dicName));
        if (count > 0) {
            return JSON.toJSONString(R.fail("数据值已重复，请修改后重试"));
        }
        if (isDefault.equals("true")) {
            dictTableService.lambdaUpdate()
                    .set(DictTable::getIsDefault, "false")
                    .eq(DictTable::getTypeId, typeId)
                    .notIn(DictTable::getDicId, Arrays.asList(dicId))
                    .update();
        }
        LambdaUpdateWrapper<DictTable> dictTableLambdaUpdateWrapper = new LambdaUpdateWrapper<>();
        dictTableLambdaUpdateWrapper.eq(
                        DictTable::getDicId, dicId)
                .set(DictTable::getDicName, dicName)
                .set(DictTable::getIsDefault, isDefault)
                .set(DictTable::getUpdateTime, new Date())
                .set(DictTable::getSort, sort);
        boolean update = dictTableService.update(dictTableLambdaUpdateWrapper);
        if (update) {
            return JSON.toJSONString(R.success("修改成功"));
        }
        return JSON.toJSONString(R.fail(LogConstant.DEFAULT_FAILURE_MESSAGE));
    }

    @Override
    public String delDic(JSONObject jsonObject) {
        //jsonobject解析获取数据Id
        String dicId = jsonObject.getString("dicId");
        boolean b = dictTableService.removeById(dicId);
        if (b) {
            return JSON.toJSONString(R.success("删除成功"));
        }
        return JSON.toJSONString(R.fail(LogConstant.DEFAULT_FAILURE_MESSAGE));
    }

    @Override
    public String getDicDetail(JSONObject jsonObject) {
        //jsonobject解析获取数据Id
        String dicId = jsonObject.getString("dicId");
        DictTable dictTable = dictTableService.getById(dicId);
        return JSON.toJSONString(R.data(dictTable));
    }

    @Override
    public String dicTypeList(JSONObject jsonObject) {
        //jsonobject解析获取类型名称
        String typeName = jsonObject.getString("typeName");
        LambdaQueryWrapper<DictType> dictTypeLambdaQueryWrapper = new LambdaQueryWrapper<>();
        dictTypeLambdaQueryWrapper.like(StringUtils.isNotEmpty(typeName), DictType::getTypeName, typeName);
        dictTypeLambdaQueryWrapper.orderByDesc(DictType::getCreateTime);
        List<DictType> list = dictTypeService.list(dictTypeLambdaQueryWrapper);
        return JSON.toJSONString(R.data(list));
    }

}
